package com.cckj.wechat.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.cckj.wechat.config.WxConfiguration;
import com.cckj.wechat.service.WxUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;


/**
 * xxx
 *
 * @author chengni
 * @date 2021/8/23 下午1:16
 */
@Service
public class WxUserServiceImpl implements WxUserService {

    @Override
    public WxMaJscode2SessionResult login(String code) throws WxErrorException {
        WxMaUserService userService = WxConfiguration.getService().getUserService();
        return userService.getSessionInfo(code);
    }

    @Override
    public WxMaUserInfo info(String sessionKey, String rawData, String signature, String encryptedData, String iv) throws WxErrorException {
        WxMaService service = WxConfiguration.getService();
        // 用户信息校验
        if (!service.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            throw new WxErrorException("WxUser check failed");
        }
        // 解密用户信息
        return service.getUserService().getUserInfo(sessionKey, encryptedData, iv);
    }

    @Override
    public WxMaPhoneNumberInfo phone(String sessionKey, String rawData, String signature, String encryptedData, String iv) throws WxErrorException {
        WxMaService service = WxConfiguration.getService();
        // 用户信息校验
        if (!service.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            throw new WxErrorException("WxUser check failed");
        }

        return service.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
    }
}
